<template>
  <view class="container">
    <view class="header">
      <text class="title">打印机设置</text>
      <uni-button type="primary" size="mini" @click="fetchPrinters">刷新列表</uni-button>
    </view>

    <uni-table :border="true">
      <uni-tr>
        <uni-th>打印机名称</uni-th>
        <uni-th>状态</uni-th>
        <uni-th>操作</uni-th>
      </uni-tr>
      <uni-tr v-for="printer in printers" :key="printer.name">
        <uni-td>{{ printer.name }}</uni-td>
        <uni-td>{{ printer.status }}</uni-td>
        <uni-td>
          <uni-button type="default" size="mini" @click="setDefaultPrinter(printer)">设为默认</uni-button>
          <uni-button type="primary" size="mini" @click="testPrinter(printer)">测试打印</uni-button>
        </uni-td>
      </uni-tr>
    </uni-table>

    <view class="footer">
      <uni-button type="primary" size="mini" @click="saveSettings">保存设置</uni-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      printers: [],
      defaultPrinter: null,
    };
  },
  methods: {
    fetchPrinters() {
      // 通过后端接口获取打印机列表
      uni.request({
        url: '/api/printers',
        method: 'GET',
        success: (res) => {
          this.printers = res.data.printers;
        },
        fail: (err) => {
          uni.showToast({ title: '获取打印机列表失败', icon: 'none' });
        },
      });
    },
    setDefaultPrinter(printer) {
      this.defaultPrinter = printer;
      uni.showToast({ title: `已设置 ${printer.name} 为默认打印机`, icon: 'success' });
    },
    testPrinter(printer) {
      // 通过后端接口测试打印
      uni.request({
        url: '/api/printers/test',
        method: 'POST',
        data: { printer: printer.name },
        success: (res) => {
          uni.showToast({ title: '测试打印成功', icon: 'success' });
        },
        fail: (err) => {
          uni.showToast({ title: '测试打印失败', icon: 'none' });
        },
      });
    },
    saveSettings() {
      if (!this.defaultPrinter) {
        uni.showToast({ title: '请选择默认打印机', icon: 'none' });
        return;
      }
      // 通过后端接口保存默认打印机设置
      uni.request({
        url: '/api/printers/default',
        method: 'POST',
        data: { printer: this.defaultPrinter.name },
        success: (res) => {
          uni.showToast({ title: '设置保存成功', icon: 'success' });
        },
        fail: (err) => {
          uni.showToast({ title: '设置保存失败', icon: 'none' });
        },
      });
    },
  },
  mounted() {
    this.fetchPrinters();
  },
};
</script>

<style scoped>
.container {
  padding: 10px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

uni-button {
  margin-left: 10px;
}
</style>
